// 实现这个项目的构建任务
const { src, dest, series, parallel, watch } = require('gulp')

const browserSync = require('browser-sync') // 类似于express
const del = require('del')
const loadPlugins = require('gulp-load-plugins')

const plugins = loadPlugins() // 自动加载glup的插件
const bs = browserSync.create() // 创建开发服务器

const clean = () => {
    return del(['dist', 'temp']) // 返回promise
}

const style = () => {
    return src('src/assets/styles/*.scss', {base: 'src'}) // 保留src下目录结构
        .pipe(plugins.sass())
        .pipe(dest('temp')) // 只写目标文件夹即可
}

const script = () => {
    return src('src/assets/scripts/*.js', {base: 'src'}) // 保留src下目录结构
        .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
        .pipe(dest('temp')) // 只写目标文件夹即可
}
const data = {
    menus: [],
    pkg: require('./package.json'),
    date: new Date()
}

const page = () => {
    return src('src/*.html', {base: 'src'})
        .pipe(plugins.swig({ data })) // 传数据
        .pipe(dest('temp'))
}

const image = () => {
    return src('src/assets/images/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const font = () => {
    return src('src/assets/fonts/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
    return src('public/**', {base: 'public'})
        .pipe(dest('dist'))
}

const useref = () => {
    return src('temp/*.html', { base: 'temp' })
        .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
        // html js css
        .pipe(plugins.if(/\.js$/, plugins.uglify()))// 判断js文件并进行压缩
        .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
        .pipe(plugins.if(/\.html$/, plugins.htmlmin({
            coolapseWhitespace: true, // 空格换行
            minifyCSS: true, // 行内样式,style标签内
            minifyJS: true // script标签内
        })))
        .pipe(dest('dist'))
}

const serve = () => {
    watch('src/assets/styles/*.scss', style)
    watch('src/assets/scripts/*.js', script)
    watch('src/*.html', page) // 监听src目录源文件变化

    watch([
        'src/assets/images/**',
        'src/assets/fonts/**',
        'public/**'
    ], bs.reload)
    // 初始化服务器配置
    bs.init({
        port: 8081,
        notify: false,
        files: 'temp/**', // 被监听的文件，热更新刷新浏览器
        server: {
            baseDir: ['temp', 'src', 'public'], // 网站根目录，数组形式，顺序查找
            // routes里定义了路径，在html里就会用这个指定的，若没有才用上面baseDir的值
            routes: {
                '/node_modules': 'node_modules' // 相对路径，相对于项目根路径
            }
        }
    })
}

const compile = parallel(style, script, page)

const dev = series(compile, serve)

const build = series(clean, parallel(series(compile, useref), image, font, extra))

module.exports = {
    clean,
    dev,
    build
}